
import { Empty, Progress, Radio, RadioChangeEvent, Select, Table } from "antd"
import React, { useEffect, useState } from "react"
import * as echarts from "echarts"
import { $AddZero, $ScientificNotation, $eventBus } from "../../../../../../common/utils"
import leftImage from "../../../../../../assets/image/通用／icon／line／left@2x.png"
import rightImage from "../../../../../../assets/image/icon_line_right@2x.png"
import emptyImage from "../../../../../../assets/image/反馈／异常／空态@2x.png"
import seeMoreImage from "../../../../../../assets/image/icon_line_right@2x (1).png"
import lessModule from "./index.module.less"
import { useNavigate } from "react-router-dom"
import { $Http } from "../../../../../../network"


// 浮层组件-左上方组件
interface layerComponentLeftTopComponentInterface {
    sourceData: object
}
const LayerComponent_LeftTopComponent: React.FC<layerComponentLeftTopComponentInterface> = (props) => {

    const progressLabel: Function = () => {
        return (
            <div className={`${lessModule["layerComponentLeftTopComponent-main__progress"]}`}>
                <span>{props.sourceData?.["total_num"]}</span>
                <span className={`${lessModule["main-progress__label"]}`}>总数</span>
            </div>
        )
    }

    const panelList = [
        {
            label: "在线", key: "online_num", color: "#30BF78"
        },
        {
            label: "告警", key: "alarm_num", color: "#FAAD14"
        },
        {
            label: "故障", key: "error_num", color: "#F4664A"
        },
        {
            label: "离线", key: "offline_num", color: "#7A8F99"
        },
    ]

    return (
        <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel"]} ${lessModule["homePagePanoramicMonitoringPageLayerComponent-left__layerComponentLeftTopComponent"]}`}>

            <header className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel__header"]}`}>站点状态统计</header>
            <div className={`${lessModule["left-layerComponentLeftTopComponent__main"]}`}>

                <Progress type="circle" percent={100} width={100} strokeWidth={1} strokeColor={{
                    '0%': '#2BEDE6',
                    '100%': '#17A1E6',
                }} format={() => progressLabel()} />
                <div className={`${lessModule["layerComponentLeftTopComponent-main__panel"]}`}>
                    {
                        panelList.map((item, idx) => {
                            return (
                                <div key={"panel" + idx} className={`${lessModule["main-panel__row"]}`}
                                    style={{ borderTop: idx && "1px solid  rgba(23, 161, 230, 0.3)", paddingLeft: idx === 2 ? "59px" : "69px", left: idx == 2 ? "0" : "-10px" }}>
                                    {item.label}：
                                    <span style={{ color: item.color }}>{props.sourceData?.[item["key"]]}</span>
                                </div>)
                        })
                    }
                </div>
            </div>
        </div>
    )
}

// 浮层组件-左下方组件
interface layerComponentLeftBottomComponentInterface {
    sourceList: Array<object>
}

const LayerComponent_LeftBottomComponent: React.FC<layerComponentLeftBottomComponentInterface> = (props) => {

    return (
        <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel"]} ${lessModule["homePagePanoramicMonitoringPageLayerComponent-left__layerComponentLeftBottomComponent"]}`}>
            <header className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel__header"]}`}>能耗统计</header>
            <div className={`${lessModule["left-layerComponentLeftBottomComponent__main"]}`}>
                {
                    props.sourceList?.map((item, idx) => {
                        return (
                            <div key={"source" + idx} >
                                {
                                    item?.["list"]?.length > 0 && <div className={lessModule["layerComponentLeftBottomComponent-main__block"]}>
                                        <header className={lessModule["main-block__header"]} style={{ marginTop: idx ? 16 : 0 }}>{item?.["label"]}线</header>
                                        <main className={lessModule["main-block__main"]}>
                                            {
                                                item?.["list"].map((item: object, idx: number) => {
                                                    return (
                                                        <div key={'list' + idx} className={`${lessModule["block-main__row"]}`} >
                                                            <div className={`${lessModule["main-row__idxBox"]}`} style={{ backgroundImage: idx ? "linear-gradient(270deg, rgba(153,153,153,0) 0%, #CCCCCC 100%)" : idx === 1 ? "" : idx === 2 ? "linear-gradient(270deg, rgba(230,159,18,0) 0%, #E69F12 100%)" : "linear-gradient(270deg, rgba(230,146,118,0) 0%, #E66046 100%)" }}>{$AddZero(idx + 1)}</div>
                                                            <span>{item?.["substation_name"]}</span>
                                                            <span className={`${lessModule["main-row__value"]}`}>{$ScientificNotation(item?.["substation_eledgree"])} kW·h</span>
                                                        </div>
                                                    )
                                                })
                                            }
                                        </main>
                                    </div>
                                }
                            </div>
                        )
                    })
                }
            </div>
        </div>
    )
}

// 浮层组件-中间组件
interface layerComponentCenterComponentPropsInterface {

}
const LayerComponent_CenterComponent: React.FC<layerComponentCenterComponentPropsInterface> = (props) => {

    const freewayList = [
        { label: "德会高速" },
        { label: "绵九高速" },
    ]
    let [freewayName, setFreewayName] = useState<string>("")
    const [isOpen, setIsOpen] = useState<boolean>(true)
    const stateList = [
        {
            label: "在线", color: "#2BEDE6"
        },
        {
            label: "告警", color: "#FAAD14"
        },
        {
            label: "故障", color: "#F4664A"
        },
        {
            label: "离线", color: "#7A8F99"
        },
    ]

    const change_freewayName = (value: string) => {
        freewayName = value
        setFreewayName(freewayName)
        $eventBus.emit("eventBus_freewayName", freewayName)
        http_pvmGetAlldevice()
    }
    const click_switch = () => {
        setIsOpen(!isOpen)
    }

    const click_zoom = (zoomAction: string) => {
        $eventBus.emit("eventBus_mapZoomAction", zoomAction)
    }

    const http_pvmGetAlldevice = () => {
        $Http("pvmGetAlldevice", { line_name: freewayName }).then((res) => {
            $eventBus.emit("eventBus_siteList", res["substation_list"])

        })
    }
    const init_freewayName = () => {

        freewayName = freewayList[0].label
        $eventBus.emit("eventBus_freewayName", freewayName)
        setFreewayName(freewayName)
    }
    useEffect(() => {
        init_freewayName()
        http_pvmGetAlldevice()
    }, [])
    return (
        <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-layerComponentCenterComponent"]}`}>
            <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-layerComponentCenterComponent__top"]}`}>
                <div className={`${lessModule["layerComponentCenterComponent-top__zoomBox"]}`}>
                    <div className={`${lessModule["top-zoomBox__item"]} ${lessModule["top-zoomBox__enlargeItem"]}`} onClick={() => click_zoom("enlarge")}><span className={`${lessModule["zoomBox-item__font"]}`}> + </span></div>
                    <div className={`${lessModule["top-zoomBox__item"]} ${lessModule["top-zoomBox__narrowItem"]}`} onClick={() => click_zoom("narrow")}><span className={`${lessModule["zoomBox-item__font"]}`}> - </span></div>
                </div>
                <Select
                    popupClassName="layerComponentCenterComponent-top__selectDropdown"
                    value={freewayName}
                    onChange={change_freewayName}
                    options={freewayList}
                    fieldNames={{ value: "label" }}
                />
            </div>
            <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-layerComponentCenterComponent__bottom"]}`}>
                {
                    isOpen && <div className={`${lessModule["layerComponentCenterComponent-bottom__content"]}`}>
                        {
                            stateList.map((item, idx) => {
                                return (
                                    <div className={`${lessModule["bottom-content__block"]}`} key={"stateList" + idx}>
                                        <div className={`${lessModule["content-block__radius"]}`} style={{ backgroundColor: item.color }}></div>
                                        {item.label}
                                    </div>
                                )
                            })
                        }
                    </div>
                }
                <div className={`${lessModule["layerComponentCenterComponent-bottom__switch"]}`} onClick={click_switch}>
                    <img className={`${lessModule["bottom-switch__image"]}`} src={isOpen ? leftImage : rightImage} />
                </div>
            </div>
        </div>
    )
}

// 浮层组件-右上方组件
const LayerComponent_RightTopComponent: React.FC = () => {

    let [siteList, setSiteList] = useState<Array<object>>([])
    let [sourceData, setSourceData] = useState<object>([])
    let [siteName, setSiteName] = useState<string>("")
    let [radioValue, setRadioValue] = useState<string>("")
    let [myInterval, setMyInterval] = useState<any>(null)

    let [echartsHeight, setEchartsHeight] = useState<number>(0)
    const change_siteName = (value: string) => {
        siteName = value
        radioValue = JSON.parse(`[${siteName?.split(",[")?.[1]}`)?.[0]
        setSiteName(siteName)
        setRadioValue(radioValue)
        http_pvmQueryRate()
    }

    const change_radioGroup = (e: RadioChangeEvent) => {
        radioValue = e.target.value
        setRadioValue(radioValue)
        http_pvmQueryRate()
    }

    let echartsTop: echarts.ECharts
    let echartsBottom: echarts.ECharts
    const init_echarts = () => {
        echartsTop?.dispose()
        echartsBottom?.dispose()
        echartsTop = echarts.init(document.getElementById("echartsTop") as HTMLElement)
        echartsBottom = echarts.init(document.getElementById("echartsBottom") as HTMLElement)
        draw_echarts()
    }
    const draw_echarts = () => {
        const xAxis = {
            type: 'category',
            axisLabel: {
                fontSize: 12,
                fontWeight: 400,
                color: "#8FB8CC",
                lineHeight: 15
            },
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: "rgba(23, 161, 230, 0.3)"
                }
            },
        }

        const seriesData = {
            type: 'bar',
            barWidth: 24,

            label: {
                show: true,
                position: 'top',
                formatter: (data: object) => {
                    return data?.["name"] === "电压暂降" ? `${data["data"]}次` : `${$ScientificNotation(data["data"])}%`
                },
                color: "#2BEDE6",
            },
            itemStyle: {
                //颜色渐变
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 1, color: "rgba(23,161,230,0.2)" },
                    { offset: 0, color: "rgba(23,161,230,0.8)" },
                ]),
                borderWidth: 0,
            },
        }


        const option = {
            tooltip: {
                backgroundColor: "rgba(13, 89, 128, 0.9)",
                borderColor: "#17A1E6",
                formatter(params: object) {
                    return `
                            <div class="${lessModule["layerComponentRightTopComponent-main__tooltip"]}">
                            <span>${params["name"]}</span>
                                <div class="${lessModule["main-tooltip__row"]}">
                                    <div class="${lessModule["tooltip-row__legend"]}"></div>
                                    <div>${$ScientificNotation(params["value"])}</div>
                                </div>
                            </div>`
                },
            },

            yAxis: {
                type: 'value',
                axisLabel: {
                    fontSize: 12,
                    fontWeight: 400,
                    color: "#7A8F99"
                },
                splitLine: {
                    lineStyle: {

                        color: "rgba(23, 161, 230, 0.3)"
                    }
                },
            },


        };

        const echartsTopOption = {
            ...option,
            grid: {
                top: 24,
                right: 8,
                bottom: 44
            },
            xAxis: {
                ...xAxis,
                data: ['电压偏差', '频率偏差', '电压暂降']
            },
            series: [
                {
                    ...seriesData,
                    data: [sourceData?.["voloffset_rate"], sourceData?.["fre_offset_rate"], sourceData?.["vol_down_rate"]],

                    animation: false,
                }
            ]
        }
        const echartsBottomOption = {
            ...option,

            grid: {
                top: 32,
                right: 8,
                bottom: 60
            },
            xAxis: {
                ...xAxis,
                data: ['不平衡度', '电压波动', '谐波电压总 \n 畸变率'],

            },
            series: [
                {
                    ...seriesData,
                    data: [sourceData?.["unb_rate"], sourceData?.["wave_rate"], sourceData?.["thd_rate"]],
                    animation: false,
                }
            ]
        }

        echartsTop.setOption(echartsTopOption);
        echartsBottom.setOption(echartsBottomOption);
    }

    const eventBus_on = () => {
        // 高速名称
        $eventBus.addListener("eventBus_siteList", (res) => {
            siteList = []
            siteName = ""
            radioValue = ""
            res.forEach((item: object, idx: number) => {
                siteList[idx] = {
                    label: item["substation_name"],
                    value: item["substation_name"] + "," + JSON.stringify(item["monitor_list"])
                }
            });
            siteName = siteList?.[0]?.["value"]
            radioValue = siteName ? JSON.parse(`[${siteName?.split(",[")?.[1]}`)?.[0] : ""
            setSiteList([...siteList])
            setSiteName(siteName)
            setRadioValue(radioValue)
            http_pvmQueryRate()
        })
    }
    const eventBus_off = () => {
        // 高速名称
        $eventBus.removeAllListeners("eventBus_siteList")
    }
    const http_pvmQueryRate = () => {
        clearInterval(myInterval)
        const func_execute = () => {

            $Http("pvmQueryRate", { substation_name: siteName?.split(",")?.[0], figure_name: radioValue }).then((res) => {
                sourceData = res
                setSourceData({ ...sourceData })
                init_echarts()
            })
        }

        func_execute()
        myInterval = setInterval(() => {
            func_execute()
        }, 3000)
        setMyInterval(myInterval)
    }



    useEffect(() => {
        const radioGroupClientHeight = document.getElementById("radioGroup")?.clientHeight ?? 0
        echartsHeight = 540 - 58 - radioGroupClientHeight
        setEchartsHeight(echartsHeight)
    }, [siteName])

    // 初始化
    useEffect(() => {
        eventBus_on()
        // 销毁
        return () => {
            eventBus_off()
        }
    }, [])
    useEffect(() => {
        // 销毁
        return () => {
            clearInterval(myInterval)
            setMyInterval(myInterval)
        }
    }, [sourceData])
    useEffect(() => {
        myInterval = null
        eventBus_on()
    }, [])

    return (
        <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel"]} ${lessModule["homePagePanoramicMonitoringPageLayerComponent-right__layerComponentRightTopComponent"]}`}>
            <div className={`${lessModule["right-layerComponentRightTopComponent__header"]}`}>
                <header className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel__header"]}`}>电压合格率</header>
                <Select
                    popupClassName="layerComponentRightTopComponent-header__selectDropdown"
                    value={siteName}
                    onChange={change_siteName}
                    options={siteList}
                />
            </div>
            <div className={`${lessModule["right-layerComponentRightTopComponent__main"]}`}>
                <Radio.Group className={`${lessModule["layerComponentRightTopComponent-main__radioGroup"]}`} id="radioGroup" onChange={change_radioGroup} value={radioValue}>
                    {
                        siteName && JSON.parse(`[${siteName?.split(',[')?.[1]}`)?.map((item: string, idx: number) => {
                            return <Radio key={'radio' + idx} value={item}>{item}</Radio>
                        })
                    }
                </Radio.Group>
                <div className={`${lessModule["layerComponentRightTopComponent-main__echartsTop"]}`} style={{ height: echartsHeight / 2 - 5 }} id="echartsTop" ></div>
                <div className={`${lessModule["layerComponentRightTopComponent-main__echartsBottom"]}`} style={{ height: echartsHeight / 2 + 5 }} id="echartsBottom"></div>
            </div>
        </div>
    )
}

// 浮层组件-右下方组件
const LayerComponent_RightBottomComponent: React.FC = () => {
    const navigate = useNavigate()
    const columnList = [{ title: '时间', dataIndex: 'event_time', }, { title: '站点', dataIndex: 'event_point', }, { title: '类型', dataIndex: 'event_type', },]
    let [myInterval, setMyInterval] = useState<any>(null)
    let [sourceList, setSourceList] = useState<Array<object>>([])
    const className_tableRow = (record: object, idx: number) => {
        return idx % 2 ? "" : lessModule["layerComponentRightBottomComponent-main__tableRow"]
    }
    const http_alarmEvent = () => {
        const func_execute = () => {
            $Http("transiantEvent").then((res) => {
                sourceList = res["transiant_event"]
                setSourceList([...sourceList])
            })
        }
        func_execute()
        myInterval = setInterval(() => {
            func_execute()
        }, 3000)
        setMyInterval(myInterval)
    }
    useEffect(() => {
        // 销毁
        return () => {
            clearInterval(myInterval)
            setMyInterval(myInterval)
        }
    }, [sourceList])
    useEffect(() => {
        http_alarmEvent()
    }, [])
    return (
        <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel"]} ${lessModule["homePagePanoramicMonitoringPageLayerComponent-right__layerComponentRightBottomComponent"]}`}>
            <header className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-panel__header"]}`}>系统事件</header>
            <div className={`${lessModule["right-layerComponentRightBottomComponent__main"]}`}>

                <Table rowKey={(record) => record["time"]} locale={{
                    emptyText: <Empty image={emptyImage} imageStyle={{
                        width: 64,
                        height: 42,
                    }} />
                }}
                    columns={columnList}
                    dataSource={sourceList.splice(0, 5)}
                    pagination={false}
                    rowClassName={className_tableRow}
                />

                <div className={`${lessModule["layerComponentRightBottomComponent-main__seeMore"]}`}>
                    <span onClick={() => { navigate(`/home/dataManagement/eventStatistics`) }}>查看全部（{sourceList?.length <= 99 ? sourceList?.length : "99+"}）</span>
                    <img className={`${lessModule["main-seeMore__image"]}`} src={seeMoreImage} />
                </div>

            </div>
        </div>
    )
}

// 主页-全景监控页面-浮层组件
const HomePage_PanoramicMonitoringPage_LayerComponent: React.FC = () => {
    let [realMapSourceData, setRealMapSourceData] = useState<object>({})
    let [realMapInterval, setRealMapInterval] = useState<any>(null)
    const http_realMap = () => {
        clearInterval(realMapInterval)
        const func_execute = () => {
            $Http("realMap").then((res) => {
                const substationEneryList: Array<{ label: string, list: Array<object> }> = [{ label: "德会", list: [] }, { label: "绵九", list: [] }]
                res?.["substation_enery"]?.forEach((item: object) => {
                    substationEneryList.find((substationEneryItem: object) => item["line_name"].includes(substationEneryItem["label"]))?.["list"]?.push(item)
                });
                res["substation_enery"] = substationEneryList
                realMapSourceData = res
                setRealMapSourceData({ ...realMapSourceData })

            })
        }
        func_execute()
        realMapInterval = setInterval(() => {
            func_execute()
        }, 3000)
        setRealMapInterval(realMapInterval)
    }
    useEffect(() => {
        http_realMap()
        return () => {
            clearInterval(realMapInterval)
            setRealMapInterval(realMapInterval)
        }
    }, [])
    return (
        <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent"]}`}>
            <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-left"]}`}>
                <LayerComponent_LeftTopComponent sourceData={realMapSourceData["substation_status"]} />
                <LayerComponent_LeftBottomComponent sourceList={realMapSourceData["substation_enery"]} />
            </div>
            <LayerComponent_CenterComponent />
            <div className={`${lessModule["homePagePanoramicMonitoringPageLayerComponent-right"]}`}>
                <LayerComponent_RightTopComponent />
                <LayerComponent_RightBottomComponent />
            </div>
        </div>
    )
}

export default HomePage_PanoramicMonitoringPage_LayerComponent